<?php

namespace App\Http\Controllers\Admin;

use App\Enums\ResponseEnum;
use App\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Spatie\Activitylog\Models\Activity;

class BasicController extends AdminController
{
    public function info()
    {
        return $this->succeed();
    }

    public function logs(Request $request)
    {
        $model = Activity::causedBy($request->user())->select(['log_name', 'description', 'subject_id', 'subject_type', 'created_at'])
            ->whereRaw("DATE_SUB(CURDATE(),INTERVAL 7 DAy) <= DATE(`created_at`)");
        $total = $model->count();
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('pageSize', 10);
        $list = $model->offset(($page - 1) * $pageSize)->limit($pageSize)->get()->toArray();
        return $this->succeed([
            'total' => $total,
            'rows' => $list,
        ]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'displayName' => ['required','between:2,20']
        ]);
        $user = $request->user();
        $data = $request->only(['displayName', 'email', 'mobile', 'sex', 'describe']);
        DB::transaction(function () use ($user, $data) {
            $user->update([
                'display_name' => $data['displayName'],
                'email' => (string)$data['email'],
                'mobile' => (string)$data['mobile'],
                'sex' => (int)$data['sex'],
                'describe' => (string)$data['describe']
            ]);
            $this->createSyslog('管理员修改了信息', $data, $user);
        });
        return $this->succeed();
    }

    public function resetPassword(Request $request)
    {
        $request->validate([
            'userPassword' => ['required', 'between:8,20', Password::default()],
            'newPassword' => ['required', 'between:8,20', 'confirmed', Password::default()],
        ]);
        $newPassword = $request->get('newPassword');
        $userPassword = $request->get('userPassword');
        abort_if($newPassword === $userPassword, ResponseEnum::BASIC_USER_OLD_PASSWORD_ERROR);
        $user = $request->user();
        abort_if(!Hash::check($userPassword, $user['password']), ResponseEnum::BASIC_USER_PASSWORD_ERROR);
        DB::transaction(function () use ($user, $newPassword) {
            $user->update(['password' => bcrypt($newPassword)]);
            $user->currentAccessToken()->delete();
            $this->createSyslog('管理员重置了密码', [], $user);
        });
        return $this->succeed();
    }
}
